package com.governtalk.backend.repository;

import com.governtalk.backend.entity.Collection;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface CollectionRepository extends JpaRepository<Collection, Long> {
    
    // 根据用户ID获取收藏列表
    Page<Collection> findByUserIdOrderByCollectTimeDesc(Long userId, Pageable pageable);
    
    // 根据用户ID和内容类型获取收藏列表
    Page<Collection> findByUserIdAndContentTypeOrderByCollectTimeDesc(
        Long userId, Collection.ContentType contentType, Pageable pageable);
    
    // 根据用户ID和关键词搜索收藏
    @Query("SELECT c FROM Collection c WHERE c.userId = :userId AND " +
           "(c.contentTitle LIKE %:keyword% OR c.contentDescription LIKE %:keyword%) " +
           "ORDER BY c.collectTime DESC")
    Page<Collection> findByUserIdAndKeyword(@Param("userId") Long userId, 
                                            @Param("keyword") String keyword, 
                                            Pageable pageable);
    
    // 检查用户是否已收藏特定内容
    boolean existsByUserIdAndContentTypeAndContentId(Long userId, 
                                                     Collection.ContentType contentType, 
                                                     Long contentId);
    
    // 根据用户ID和内容ID查找特定收藏记录
    Collection findByUserIdAndContentTypeAndContentId(Long userId, 
                                                      Collection.ContentType contentType, 
                                                      Long contentId);
    
    // 删除用户的所有收藏
    void deleteByUserId(Long userId);
    
    // 删除用户特定类型的收藏
    void deleteByUserIdAndContentType(Long userId, Collection.ContentType contentType);
    
    // 获取用户最近收藏的内容
    List<Collection> findTop10ByUserIdOrderByCollectTimeDesc(Long userId);
    
    // 根据时间范围获取收藏
    Page<Collection> findByUserIdAndCollectTimeBetweenOrderByCollectTimeDesc(
        Long userId, LocalDateTime startTime, LocalDateTime endTime, Pageable pageable);
}
